//
//  TBBLEWriteCharacterAction.m
//  TBSDK
//
//  Created by nexgo on 2017/10/27.
//  Copyright © 2017年 truth. All rights reserved.
//

#import "TBBLEWriteCharacterAction.h"


@interface TBBLEWriteCharacterAction(){
    NSData* sendData;
    
    int sendIndex;
}
@end

@implementation TBBLEWriteCharacterAction

- (instancetype _Nullable )init:(CBCharacteristic*_Nullable)character data:(NSData*_Nullable)sendDataTmp option:(TBBLEBaseOption*_Nullable)optionTmp{
    self = [super init:TBBLEACTION_WRITECHACT option:optionTmp];
    if (self) {
        _character = character;
        sendData = sendDataTmp;
        sendIndex = 0;
    }
    
    return self;
}

// 获取需要发送的数据
-(NSData*_Nullable)getPerData{
    NSLog(@"getPerData");
    if((sendData == nil) || (sendIndex >= sendData.length)){  // 源数据为空 或 数据已经取完
        self.status = TBBLEACTION_DONE;
        if(sendData == nil){
            NSLog(@"sendData == nil");
        }else{
           NSLog(@"sendIndex >= sendData.length, ->%d, data len->%d", sendIndex, sendData.length);
        }
        return nil;
    }
    
    if((sendIndex + self.option.perLen) > sendData.length){  // 剩余数据不足一整个桢
        NSData* sendDataTmp = [sendData subdataWithRange:NSMakeRange(sendIndex, sendData.length-sendIndex)];
        sendIndex += (sendData.length-sendIndex);
        NSLog(@"sendIndex 1->%d", sendIndex);
        return sendDataTmp;
    }
    NSData* sendDataTmp = [sendData subdataWithRange:NSMakeRange(sendIndex, self.option.perLen)];
    sendIndex += self.option.perLen;
    
    NSLog(@"sendIndex 2->%d", sendIndex);
    return sendDataTmp;
}

// 复位操作
-(void)resetAction{
    self.status = TBBLEACTION_WAITTING;
    sendIndex = 0;
}

@end

@implementation TBBLEWriteCharacterActionCB

@end
